package pw.goyd.game.handler.imp;

import pw.goyd.game.api.DBDone;
import pw.goyd.game.api.LuckyPoolImp;
import pw.goyd.game.constant.setting.LuckyPool;
import pw.goyd.game.handler.Handler;
import pw.goyd.game.logic.LuckyAwardResponse;
import pw.goyd.game.manager.GameManager;
import pw.goyd.game.model.LuckyAward;
import pw.goyd.game.server.Log;
import pw.goyd.game.server.LoginList;
import pw.goyd.protocol.model.Response;
import pw.goyd.subscribe.PlayerCustomer;

/**
 * 抽奖处理
 * Created by StanWind on 16/11/5.
 */
public class LUCKYAWARD extends Handler {
    @Override
    public void handle() {
        PlayerCustomer p = LoginList.getPlayer(ctx.getChannel().getId());
        if (p == null) {
            Log.getLogger().error("空指针--->ChannelID[" + ctx.getChannel().getId() + "]");
            return;
        }

        LuckyAwardResponse luckyAwardResponse = new LuckyAwardResponse();
        if (p.getLucky_count() > 0) {
            luckyAwardResponse.setState(0);                                 //  置状态 正常
            LuckyAward luckyAward = LuckyPoolImp.getRandAward();            //  抽取物品
            luckyAwardResponse.setLuckyAward(luckyAward);                   //  放入回写
            if (luckyAward.getLuckyType() != LuckyPool.LuckyType.Again)      //  不是再来一次
                p.setLucky_count(p.getLucky_count() - 1);                   //  减少抽奖次数
            p.saveLuckyAward(luckyAward);                                   //  奖励保存
            DBDone.updateLucky(p);                                          //  更新抽奖次数
            Log.getLogger().info("玩家->" + p.getNickname() + " 抽取了->" + luckyAward);
            //TODO 有公告
            if (luckyAward.getWeight() == 1 && luckyAward.getLuckyType() == LuckyPool.LuckyType.Gold) {
                GameManager.sendAnnounceMsg("恭喜玩家在幸运大转盘活动中抽取了 " + luckyAward.getValue() + "个金币");
            } else if (luckyAward.getWeight() == 1 && luckyAward.getLuckyType() == LuckyPool.LuckyType.Diamond) {
                GameManager.sendAnnounceMsg("恭喜玩家在幸运大转盘活动中抽取了 " + luckyAward.getValue() + "个钻石");
            }

        } else {
            luckyAwardResponse.setState(1);
            luckyAwardResponse.setLuckyAward(new LuckyAward());             //  放置空物品
        }

        Response response = new Response();
        response.setCmd(CMD_LUCKYAWARD);
        response.setData(luckyAwardResponse.getBytes());
        response.setTime(0);
        this.getCtx().getChannel().write(response);
    }
}
